package cqgans.app.sunao.com.cqgans.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import cqgans.app.sunao.com.cqgans.adapter.PurchaseAdapter;
import cqgans.app.sunao.com.cqgans.bean.PageResult;
import cqgans.app.sunao.com.cqgans.bean.UserPurchase;
import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgans.widget.LoadingDialog;
import cqgans.app.sunao.com.cqgansnew.R;

/**
 * Created by sunao on 2017/6/12.
 */
@SuppressWarnings("WrongConstant")
@ContentView(R.layout.activity_home)
public class HomeActivity extends BaseActivity {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
//    @ViewInject(R.id.home_noinfo)
//    private TextView home_noinfo;
    @ViewInject(R.id.change_pwd)
    private TextView change_pwd;

    @ViewInject(R.id.tv_user_type)
    private TextView userTypeTv;
    @ViewInject(R.id.tv_purchase_status)
    private TextView userPurchaseTv;
    @ViewInject(R.id.tv_newuser)
    private TextView newUserTv;

    @ViewInject(R.id.tv_starttime)
    private TextView startTimeTv;
    @ViewInject(R.id.tv_endtime)
    private TextView endTimeTv;

    @ViewInject(R.id.refresh_layout)
    private SwipeRefreshLayout refreshLayout;

    @ViewInject(R.id.recycler)
    private RecyclerView recyclerView;
    @ViewInject(R.id.et_gas_user_number)
    private EditText userGasNoEt;
    @ViewInject(R.id.et_user_name)
    private EditText userNameEt;

    @ViewInject(R.id.et_gas_addr)
    private EditText userGasAddr;

    LoadingDialog progressDialog;
    private OptionsPickerView pvOptions;

    private int count = 20;

    private long startTime, endTime;
    private String userType = null;
    private String isNewUser = null;
    private String purchaseStatus = null;

    private PurchaseAdapter adapter;

    private String[] userTypes = new String[]{"全部", "工商用户", "居民用户"};
    private String[] purchaseStatuss = new String[]{"全部", "已购买", "未购买"};
    private String[] newUserStates = new String[]{"全部", "新用户", "老用户"};

    private PageResult<UserPurchase> pageResult;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        pageResult = new PageResult<>();
        progressDialog = new LoadingDialog(this, "数据加载中，请稍侯...");
    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitleBar("安燃通", 3);
        sharedPreferences = getSharedPreferences("cqgas", Context.MODE_PRIVATE);
        pageResult.currentPage = 1;
        pageResult.pageResults.clear();
        initLayout();
        search();
    }



    private void initLayout() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PurchaseAdapter(pageResult.pageResults);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                pageResult.currentPage ++;
                search();
            }
        });
        adapter.bindToRecyclerView(recyclerView);
        adapter.setEmptyView(R.layout.item_empty);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AppConstant.account = pageResult.pageResults.get(position);
               startActivity(new Intent(HomeActivity.this, ProductActivity.class));
            }
        });
        adapter.disableLoadMoreIfNotFullPage();
        recyclerView.setAdapter(adapter);
        findViewById(R.id.back).setVisibility(View.VISIBLE);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView close = (TextView) this.findViewById(R.id.close);
        close.setVisibility(View.GONE);
        close.setText("切换账号");
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppConstant.user = null;
                editor = sharedPreferences.edit();//获取编辑器
                editor.putInt("id", 0);
                editor.commit();
                startActivity(new Intent(HomeActivity.this, MainActivity.class));
                finish();
            }
        });
        findViewById(R.id.user).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppConstant.TARGET_URL = AppConstant.JSS_ACCOUNT_URL;
                startActivity(new Intent(HomeActivity.this, WebActivity.class));
            }
        });
        findViewById(R.id.user_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    AppConstant.TARGET_URL = AppConstant.JSS_ACCOUNT_URL;
                    startActivity(new Intent(HomeActivity.this, WebActivity.class));

            }
        });
        change_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, ChangePwdActivity.class));

            }
        });
        findViewById(R.id.rank_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, RankActivity.class));
            }
        });
        userTypeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvOptions = new OptionsPickerBuilder(HomeActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                        userTypeTv.setText(userTypes[options1]);
                        if(options1 == 0) {
                            userType = null;
                        } else {
                            userType = options1 + "";
                        }
                    }
                }).build();
                pvOptions.setPicker(Arrays.asList(userTypes));
                pvOptions.show();
                pvOptions.setTitleText("请选择用户类型");
            }
        });
        newUserTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvOptions = new OptionsPickerBuilder(HomeActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                        newUserTv.setText(newUserStates[options1]);
                        if(options1 == 0) {
                            isNewUser = null;
                        } else {
                            isNewUser = options1 + "";
                        }
                    }
                }).build();
                pvOptions.setPicker(Arrays.asList(newUserStates));
                pvOptions.show();
                pvOptions.setTitleText("是否为新用户");
            }
        });
        userPurchaseTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvOptions = new OptionsPickerBuilder(HomeActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                        userPurchaseTv.setText(purchaseStatuss[options1]);
                        if(options1 == 0) {
                            purchaseStatus = null;
                        } else {
                            purchaseStatus = options1 + "";
                        }
                    }
                }).build();
                pvOptions.setPicker(Arrays.asList(purchaseStatuss));
                pvOptions.show();
                pvOptions.setTitleText("请选择购买状态");
            }
        });

        startTimeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(HomeActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        startTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd").format(date));
                        startTime = date.getTime();
                    }
                }).build();
                 pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        endTimeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(HomeActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        endTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd").format(date));
                        endTime = date.getTime();
                    }
                }).build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        findViewById(R.id.search_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageResult.currentPage = 1;
                pageResult.pageResults.clear();
                search();
            }
        });

        findViewById(R.id.clear_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userGasNoEt.setText("");
                userNameEt.setText("");
                userGasAddr.setText("");
                startTimeTv.setText("");
                endTimeTv.setText("");
                userPurchaseTv.setText("");
                userTypeTv.setText("");
                newUserTv.setText("");
                userType = "";
                purchaseStatus = "";
                isNewUser = "";
            }
        });

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageResult.currentPage = 1;
                pageResult.pageResults.clear();
                search();
            }
        });
    }


    private void search() {
        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.QUERY_URL);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (imm.isActive()) {
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//开启或者关闭软键盘
//        }
        JSONObject mjson = new JSONObject();
        try {
            mjson.put("loginUserNo", AppConstant.user.getMobile());
            if(!TextUtils.isEmpty(userGasNoEt.getText().toString()))
                mjson.put("userNo", userGasNoEt.getText().toString());
            if(!TextUtils.isEmpty(userNameEt.getText().toString()))
                mjson.put("userName", userNameEt.getText().toString());
            if(!TextUtils.isEmpty(userGasAddr.getText().toString()))
                mjson.put("userAddress", userGasAddr.getText().toString());
            if(!TextUtils.isEmpty(userType))
                mjson.put("userType", userType);
            if(!TextUtils.isEmpty(isNewUser))
                mjson.put("isNewUser", isNewUser);
            if(!TextUtils.isEmpty(purchaseStatus))
                mjson.put("insured", purchaseStatus);
            if(!TextUtils.isEmpty(startTimeTv.getText().toString()))
                mjson.put("insuredExpiredTime_start", startTime);
            if(!TextUtils.isEmpty(endTimeTv.getText().toString()))
                mjson.put("insuredExpiredTime_end", endTime);
            if(startTime != 0 && endTime != 0 && endTime < startTime) {
                Toast.makeText(this, "过期时间不得小于投保时间", Toast.LENGTH_LONG).show();
                return;
            }
            mjson.put("page", pageResult.currentPage);
            mjson.put("count", count);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        progressDialog = new LoadingDialog(this, "加载中...");
        progressDialog.show();
        params.setAsJsonContent(true);
        params.setBodyContent(mjson.toString());
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @SuppressWarnings("WrongConstant")
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                System.out.println(result);
                progressDialog.close();
                refreshLayout.setRefreshing(false);
                try {
                    JSONObject resultJson = new JSONObject(result);
                    LogUtil.i(resultJson.toString());
                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                        Gson gson = new Gson();
                        if (resultJson.has("data") && null != resultJson.get("data")
                                && resultJson.getJSONObject("data").has("page")
                                && null != resultJson.getJSONObject("data").get("page")) {
                            PageResult<UserPurchase> pr = gson.fromJson(resultJson.getJSONObject("data").get("page").toString(), new TypeToken<PageResult<UserPurchase> >(){}.getType());
                            pageResult.currentPage = pr.currentPage;
                            pageResult.totalPage = pr.totalPage;
                            pageResult.countOfCurrentPage = pr.countOfCurrentPage;
                            pageResult.totalCount = pr.totalCount;
                            pageResult.pageResults.addAll(pr.pageResults);
                            adapter.setNewData(pageResult.pageResults);
                            if(pageResult.currentPage == pageResult.totalPage) {
                                adapter.loadMoreEnd(false);
                            }
                        } else {
                            Toast.makeText(HomeActivity.this, "请求错误,请稍后再试", 1000).show();
                        }
                    } else {
                        if(resultJson.has("msg")) {
                            Toast.makeText(HomeActivity.this, resultJson.getString("msg"), 1000).show();
                        } else {
                            Toast.makeText(HomeActivity.this, "请求错误,请稍后再试", 1000).show();
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.close();
                LogUtil.e(ex.getMessage());
                Toast.makeText(HomeActivity.this, ex.getMessage(), 1000).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.close();

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
